package com.example.yudaoly.security;


import com.example.yudaoly.service.UsersService;
import com.example.yudaoly.utils.JwtUtil;
import com.example.yudaoly.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UsersService usersService;

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, ServletException, IOException {

        String token = request.getHeader("token");
        // 不存在token
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }

        //存在token
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String userId = claims.getSubject();

            //验证会话是否过期
            LoginUser loginUser = redisCache.getCacheObject("login:"+userId);
            if(loginUser == null){
                //放行
//                filterChain.doFilter(request,response);
//                return;
                throw new RuntimeException("token已经过期了！");
            }

            //修改过期时间
            redisCache.expire("login:"+loginUser.getUsers().getId(),2,TimeUnit.MINUTES);
//            redisCache.setCacheObject("loginUser::" + username, token,2, TimeUnit.MINUTES);

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null
                    ,loginUser.getAuthorities());

            // 告诉springsecurity 当前请求是哪个用户的
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //放行
            filterChain.doFilter(request, response);

        } catch (Exception e) {
            throw new RuntimeException("token不合法");
        }
    }
}
